package com.joint.web.action.com;

import com.csvreader.CsvWriter;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.bean.search.rule.Rule;
import com.fz.us.base.util.Identities;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.entity.Dict;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.Employees;
import com.joint.core.service.EmployeesService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxEmployeeinfoAction extends BaseFlowAction {

    @Resource
    private EmployeesService employeesService;
    private File filedata;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "employeeinfo";
    }

    /**
     * 员工信息统计
     * @return
     */
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(org.apache.commons.lang.StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("nature","0");
        params.put("ifJob","0");

        //params.put("type",0);
        //已归档
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=employeesService.findByPagerAndLimit(true, "employees", pager, params);

        List<Employees> eList;
        if (pager.getTotalCount() > 0){
            eList = (List<Employees>) pager.getList();
        }else{
            eList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Employees e:eList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",e.getId());
            rMap.put("name",e.getName());
            rMap.put("political",(e.getPartyMember()!=null&&e.getPartyMember().equals("0"))?"党员":"非党员");

            rMap.put("birthday", DataUtil.DateToString(e.getBirthDate(),"yyyy-MM-dd"));
            rMap.put("age",e.getAge());
            rMap.put("gender",e.getGender());
            rMap.put("cardId",e.getCardID());
            rMap.put("edu",e.getHighestDegree()==null?"":e.getHighestDegree().getName());
            rMap.put("post",e.getEmpPost()==null?"":e.getEmpPost().getName());
            rMap.put("dep",e.getDep()==null?"":e.getDep().getName());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        LogUtil.info("dataRows"+dataRows);
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 导入excel
     * @return
     */
    public ResponseEntity<byte[]> exportExcel() {
        Company company = usersService.getCompanyByUser();
        Map<String, Object> params = new HashMap<String, Object>();
        params = getSearchFilterParams(_search, params, filters);
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("nature","0");
        params.put("ifJob","0");

        //params.put("type",0);
        //已归档
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        File file = createEmployeeInfoFile(company, params);
        ResponseEntity responseEntity = null;
        if (null != file) {
            try {
                InputStream inputStream = new FileInputStream(file);
                setResponseFileDownload(inputStream, file.getName());
                //    downloadRecordToFile(f, company);
            } catch (Exception e) {

            }
        }
        file.delete();
        return null;    }

    public File createEmployeeInfoFile(Company company,Map<String, Object> params) {
        long maxCount = 10000L;
        // 开始执行导出
        Pager pager = new Pager(1, maxCount);
        pager=employeesService.findByPagerAndLimit(true, "employees", pager, params);
        List<Employees> employeesList = (List<Employees>) pager.getList();

        File f = new File("员工信息统计表.csv");
        String absolutePath = f.getAbsolutePath();
        try {
            String csvFilePath = absolutePath;
            CsvWriter wr = new CsvWriter(csvFilePath, ',',
                    Charset.forName("GBK"));
            String[] header = {"姓名","政治面貌","部门","性别","年龄","身份证号码","学历","职称"};
            wr.writeRecord(header);
            if (employeesList != null && employeesList.size() > 0) {
                for (Employees employees : employeesList) {
                    String[] contents = {
                            employees.getName(),
                            (employees.getPartyMember()!=null&&employees.getPartyMember().equals("1"))?"党员":"非党员",
                            employees.getDep()!=null?employees.getDep().getName():"",
                            employees.getGender(),
                            employees.getAge(),
                            employees.getCardID(),
                            employees.getHighestDegree()!=null?employees.getHighestDegree().getName():"",
                            employees.getEmpPost()!=null?employees.getEmpPost().getName():""


                    };
                    wr.writeRecord(contents);
                }
            }
            wr.close();
            return f;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return f;
    }



    public void setResponseFileDownload(InputStream fs,String fileName){
        try {
            HttpServletResponse response = getResponse();
            BufferedInputStream bins=new BufferedInputStream(fs);//放到缓冲流里面
            OutputStream outs = response.getOutputStream();//获取文件输出IO流
            BufferedOutputStream bouts=new BufferedOutputStream(outs);
            response.setContentType("application/x-download");//设置response内容的类型
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(), "ISO8859-1") + "\"");
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            //开始向网络传输文件流
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();//这里一定要调用flush()方法
            fs.close();
            bins.close();
            outs.close();
            bouts.close();
        }catch (Exception e){

        }

    }
/*
    public void exportExcel()  {
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(org.apache.commons.lang.StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("nature","0");
        params.put("ifJob","0");

        //params.put("type",0);
        //已归档
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=employeesService.findByPagerAndLimit(true, "employees", pager, params);

        List<Employees> eList;
        if (pager.getTotalCount() > 0){
            eList = (List<Employees>) pager.getList();
        }else{
            eList = new ArrayList<>();
        }
        OutputStream outputStream = null;
        // String now  = DataUtil.DateToString(new Date(),"yyyyMMddHHmmss");
        // String rand = CommonUtil.getRandomString(6);
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet("Sheet1");
        for(int i=0; i<=7;i++){
            sheet.setColumnWidth(i, 20 * 256);
        }
        CellStyle style = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
        style.setFont(font);
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("政治面貌");
        row.createCell(2).setCellValue("部门");
        row.createCell(3).setCellValue("性别");
        row.createCell(4).setCellValue("年龄");
        row.createCell(5).setCellValue("身份证号码");
        row.createCell(6).setCellValue("学历");
        row.createCell(7).setCellValue("职称");
        for(int i=0; i<=7;i++){
            row.getCell(i).setCellStyle(style);
        }
        String fileName = "员工信息统计表.xls";
        */
/*for(Employees employees:academicList){
            Date visitTime = academic.getVisitTime();
            if(visitTime == null ){
                continue;
            }
            Date date1 = DataUtil.StringToDate(DataUtil.DateToString(visitTime));
            if(StringUtils.isNotEmpty(beginTime) && DataUtil.DateDiff(date1, DataUtil.StringToDate(beginTime))< 0){
                continue;
            }
            if(StringUtils.isNotEmpty(endTime) && DataUtil.DateDiff(date1, DataUtil.StringToDate(endTime))> 0){
                continue;
            }
            eList.add(academic);
        }*//*

        for(int i=0; i<eList.size(); i++){
            Employees employees = eList.get(i);
            row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(employees.getName());
            row.createCell(1).setCellValue((employees.getPartyMember()!=null&&employees.getPartyMember().equals("1"))?"党员":"非党员");
            row.createCell(2).setCellValue(employees.getDep()!=null?employees.getDep().getName():"");
            row.createCell(3).setCellValue(employees.getGender());
            row.createCell(4).setCellValue(employees.getAge());
            row.createCell(5).setCellValue(employees.getCardID());
            row.createCell(6).setCellValue(employees.getHighestDegree()!=null?employees.getHighestDegree().getName():"");
            row.createCell(7).setCellValue(employees.getEmpPost()!=null?employees.getEmpPost().getName():"");
        }
        try {
            outputStream = new FileOutputStream("/temp/"+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        OutputStream out = null;
        HttpServletRequest request = ServletActionContext.getRequest();
        //  if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {

        //  }
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            response.setHeader("content-disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream in = null;
        try {
            in = new FileInputStream("/temp/"+fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        int i = -1;
        try {
            while ((i = in.read(buffer)) != -1) {
                out.write(buffer, 0, i);
            }
            out.flush();
            out.close();
            in.close();
            out = null;
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
*/


}
